package com.lis.scf.service.impl;

//import com.enterprise.common.enums.BusinessExceptionEnum;
//import com.enterprise.dto.LoginDTO;
//import com.enterprise.dto.LoginResponseDTO;
//import com.enterprise.dto.UserInfoDTO;
//import com.enterprise.entity.Company;
//import com.enterprise.entity.User;
//import com.enterprise.exception.BusinessException;
//import com.enterprise.repository.UserRepository;
//import com.enterprise.service.AuthService;
//import com.enterprise.service.JwtService;
import com.lis.scf.common.dto.LoginDTO;
import com.lis.scf.common.dto.LoginResponseDTO;
import com.lis.scf.common.dto.UserInfoDTO;
import com.lis.scf.common.enums.BusinessExceptionEnum;
import com.lis.scf.entity.Company;
import com.lis.scf.entity.User;
import com.lis.scf.exception.BusinessException;
import com.lis.scf.repository.UserRepository;
import com.lis.scf.service.AuthService;
import com.lis.scf.service.JwtService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 认证服务实现类
 */
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
    /**
     * 用户登录
     *
     * @param loginDTO 登录请求参数
     * @return 登录结果（包含令牌和用户信息）
     */

    private final AuthenticationManager authenticationManager;
    private final UserRepository userRepository;
    private final JwtService jwtService;
//
    @Override
    public LoginResponseDTO login(LoginDTO loginDTO) {

        // 1. 调用Spring Security认证管理器进行身份验证
        Authentication authentication;

        System.out.println(loginDTO);


        try {
            authentication = authenticationManager.authenticate(

                    new UsernamePasswordAuthenticationToken(
                            loginDTO.getUsername(),
                            loginDTO.getPassword()
                    )
            );
        } catch (Exception e) {
            // 认证失败（用户名不存在或密码错误）
            throw new BusinessException(BusinessExceptionEnum.USERNAME_PASSWORD_ERROR);
        }

        // 2. 认证成功，将认证信息存入上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 3. 获取用户信息
        User user = userRepository.findByUsername(loginDTO.getUsername())
                .orElseThrow(() -> new BusinessException(BusinessExceptionEnum.USER_NOT_FOUND));


        System.out.println("-----"+user);

        // 4. 检查用户状态（是否激活）
        if (!user.getActive()) {
            throw new BusinessException(BusinessExceptionEnum.USER_DISABLED);
        }

        // 5. 生成JWT令牌
        String accessToken = jwtService.generateToken(user.getUsername());
        long expiresIn = jwtService.getExpirationTime() / 1000; // 转换为秒

        // 6. 组装用户信息DTO
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUserId(user.getUserId());
        userInfoDTO.setUsername(user.getUsername());
        userInfoDTO.setRealName(user.getRealName());
        userInfoDTO.setMobileNumber(user.getMobileNumber());

        // 设置企业信息
        Company company = user.getCompany();

        System.out.println("----Company====-"+company);
        if (company != null) {
            userInfoDTO.setCompany(company.getCompanyId());
            userInfoDTO.setCompanyName(company.getCompanyName());
            userInfoDTO.setCompanyType(company.getCompanyType());
        }

        // 7. 获取用户权限列表
        Set<String> permissions = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toSet());

        // 8. 返回登录结果
        return new LoginResponseDTO(accessToken, "Bearer", expiresIn, userInfoDTO, permissions);
    }
}
